package poweroftwo;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class Main {
	static PowerOfTwo p = new PowerOfTwo();
	
	public static void main(String[] args) {
		testGenerator(10,2000);
	}
	
	public static void testGenerator(int nThread, final int countAttemps) {
		final PowerOfTwo generator = new PowerOfTwo();
		final List<BigInteger> results = Collections.synchronizedList(new ArrayList<BigInteger>());
		
		//Using generator in n Threads 
		Thread[] threads = new Thread[nThread];
		for (int i=0; i<nThread; i++) {
		 threads[i]=new Thread(new Runnable() {

			@Override
			public void run() {
				BigInteger next;
				for (int i=0; i<countAttemps; i++) {
				next = generator.next();
				results.add(next);
				//System.out.println(next);
				}
			}
			 
		 });
		 threads[i].start();
		}
		
		for (int i=0; i<nThread; i++) {
			try {
				threads[i].join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		//Check for repetition and omissions
		System.out.println("All correct: "+checkResults(results));
	}
	
	public static boolean checkResults(List<BigInteger> list) {
		Collections.sort(list);
		Iterator<BigInteger> iter = list.iterator();
		BigInteger prev = iter.next();
		BigInteger current;
		BigInteger bigTwo = new BigInteger("2");
		while (iter.hasNext()) {
			current = iter.next();
			if (!current.equals(prev.multiply(bigTwo))) {
				System.out.println("Problem: "+prev+" -> "+current);
				return false;
			}
			prev = current;
		}
		return true;
	}
}
